<?php
class Image extends Model
{
	public static function install()
	{
		return array
		(
			'upload_id'		=>	'CHAR(13)',
			'title'			=>	'VARCHAR(25)',
			'description'	=>	'VARCHAR(255)',
			'extension'		=>	'ENUM("jpg", "png", "gif", "wbmp")',
			'size'			=>	'INT(10) UNSIGNED',
			'views'			=>	'INT(10) UNSIGNED',
			'date'			=>	'TIMESTAMP DEFAULT CURRENT_TIMESTAMP',
			'User_id'		=>	'INT(10) UNSIGNED',
			'private'		=>	'TINYINT(1) UNSIGNED'
		);
	}
	
	// Alpha
	public function alpha()
	{
		$in = $this->id;
		
		$index = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ';
		
		$base = strlen($index);
		
		$out = '';
		
		for($t=floor(log($in, $base)); $t>=0; $t--)
		{
			$bcp = bcpow($base, $t);
			$a   = floor($in /$bcp) % $base;
			$out = $out . substr($index, $a, 1);
			$in  = $in - ($a * $bcp);
		}
		
		return strrev($out);
	}
	
	// Output
	public function output($method)
	{
		echo '<img src="'.WEB.$method.'/'.$this->alpha().'.'.$this->extension.'" alt="'.$this->title.'" title="'.$this->title.'"/>';
	}
	
	// Title
	public function title()
	{
		return $this->title?$this->title:lang('untitled');
	}
	
	// Uploader
	public function uploader()
	{
		return $this->User_id?'<a href="'.WEB.'user/'.$this->User->username.'/">'.$this->User->username.'</a>':lang('anonymous');
	}
	
	// Submitted
	public function submitted()
	{
		$seconds = abs(time() - strtotime($this->date)) + 1;
		
		$units = array
		(
			'years_ago'		=>	60*60*24*7*30*12,
			'months_ago'	=>	60*60*24*7*30,
			'weeks_ago'		=>	60*60*24*7,
			'days_ago'		=>	60*60*24,
			'hours_ago'		=>	60*60,
			'minutes_ago'	=>	60,
			'seconds_ago'	=>	1
		);
		
		foreach($units as $unit=>$size)
		{
			if($seconds >= $size)
			{
				return lang($unit, round($seconds/$size));
			}
		}
	}
	
	// Delete
	public function delete()
	{
		db::query('DELETE FROM `'.DB_PREFIX.'Image` WHERE `id`='.$this->id);
		
		$images = array('original', 'icon', 'small', 'square', 'medium');
		
		foreach($images as $image)
		{
			if(file_exists($file = APP.'upload'.DIRECTORY_SEPARATOR.$image.DIRECTORY_SEPARATOR.$this->id.'.'.$this->extension))
			{
				unlink($file);
			}
		}
	}
}